package com.handpay.zztong.hp.nocardpay.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.ArithUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.PreviewActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.nocardpay.HistoryBankCardListBean;
import com.handpay.zztong.hp.nocardpay.MerchantTypeList;
import com.handpay.zztong.hp.nocardpay.adapter.MerchantTypeAdapter;
import com.handpay.zztong.hp.nocardpay.widget.NoCardPayListCardNoAdapter;
import com.handpay.zztong.hp.notification.model.MerchantInfo;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.handpay.zztong.hp.ui.HPBankCardEdit;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.BitmapUtil;
import com.intsig.ccrengine.CCREngine;
import com.intsig.ccrengine.ISCardScanActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import static com.handpay.zztong.hp.permission.PermissionRequestCode.REQUEST_CODE_CAMERA_GETCARDNO;
import static com.handpay.zztong.hp.permission.PermissionRequestCode.REQUEST_CODE_FINDLOCATION;

/**
 * Created by lyang on 2017/6/8.
 */

public class NoCardPayActivity extends ZZTongActivity {
    public int isCardRequestCode = 33301;
    // 0： 使用sdk内置相机模块 1：使用自定义相机模块 主要是怕更换频繁
    private int useScanType = 1;
    private ImageButton no_card_pay_camera_btn, no_card_pay_card_btn, merchant_type_btn;
    private TextView no_card_pay_user_name_tv, no_card_pays_merchant_type_tv, tv_amount;
    private HPBankCardEdit no_card_pay_card_no;
    private Button no_card_pay_next_btn, no_card_pay_cancel_btn;
    private MerchantInfo mMerchantInfo;
    private HistoryBankCardListBean mHistoryBankCardListBean;
    private PopupWindow mPopupWindow;
    private double mAmount;
    private NoCardPayListCardNoAdapter mNoCardPayListCardNoAdapter;
    private HistoryBankCardListBean.ListBean mBankCard;
    public int NoCardPayRequestCode = 1000;
    private LinearLayout ll_card, ll_merchant_type;
    private String NOCARDPAYMENTURL_MY = "https://scan.handpay.cn/";
    private String NOCARDPAYMENTURL_MY_TEST = "https://app.handbank.cn/";
    private String des3Key = "f9157944f3a7ca5ef4cac37d780dd4325dd178a724b714e8";
    /**
     * 商户类型 集合
     */
    private List<MerchantTypeList.MerchantType> typeList;
    private String mMerchantType;//商户类型名称
    private String mMerchantTypeCode;//商户类型编号
    private MerchantTypeList.MerchantType mMerchantTypeBean;
    private TextView rates_tv, service_charge_tv, arrival_amount_tv;
    private LinearLayout rates_info_ll;
    private boolean bIsShowMerchantType = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_no_card_pay);
        super.onCreate(savedInstanceState);
        mAmount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        no_card_pay_camera_btn = (ImageButton) this.findViewById(R.id.no_card_pay_camera_btn);
        no_card_pay_card_btn = (ImageButton) this.findViewById(R.id.no_card_pay_card_btn);
        merchant_type_btn = (ImageButton) this.findViewById(R.id.merchant_type_btn);
        no_card_pay_next_btn = (Button) this.findViewById(R.id.no_card_pay_next_btn);
//        no_card_pay_cancel_btn = (Button) this.findViewById(R.id.no_card_pay_cancel_btn);
        no_card_pay_card_no = (HPBankCardEdit) this.findViewById(R.id.no_card_pay_card_no);
        no_card_pay_user_name_tv = (TextView) this.findViewById(R.id.no_card_pay_user_name_tv);
        no_card_pays_merchant_type_tv = (TextView) this.findViewById(R.id.no_card_pays_merchant_type_tv);
        ll_card = (LinearLayout) findViewById(R.id.ll_card);
        no_card_pay_camera_btn.setOnClickListener(this);
        no_card_pay_card_btn.setOnClickListener(this);
        no_card_pay_next_btn.setOnClickListener(this);
        merchant_type_btn.setOnClickListener(this);
        tv_amount = (TextView) findViewById(R.id.tv_amount);
        tv_amount.setText(CommonUtils.formatMoneyDouble(ArithUtil.div(mAmount, 100d)));
        mNoCardPayListCardNoAdapter = new NoCardPayListCardNoAdapter(this);
        ll_merchant_type = (LinearLayout) this.findViewById(R.id.ll_merchant_type);
        typeList = new ArrayList<>();
        merchant_type_btn.setEnabled(false);
        findViewById(R.id.ll_arrow).setOnClickListener(this);
        rates_tv = (TextView) this.findViewById(R.id.rates_tv);
        rates_info_ll = (LinearLayout) this.findViewById(R.id.rates_info_ll);
        service_charge_tv = (TextView) this.findViewById(R.id.service_charge_tv);
        arrival_amount_tv = (TextView) this.findViewById(R.id.arrival_amount_tv);
        getMerchantInfo();
        getMrchantType();
    }

    private void getMerchantInfo() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("tradeType", "2");
        doJsonPost(this, ZZTongActivity.DO_zztGetMerchantInfo, MerchantInfo.class, params);
    }

    private void doDeleteHistoryBankCardList() {

        DialogInterface.OnClickListener okClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mPopupWindow.dismiss();
                Hashtable<String, String> params = new Hashtable<String, String>();
                params.put("tradeType", "1");
                doJsonPost(NoCardPayActivity.this, ZZTongActivity.Do_DeleteHistoryBankCardList, ResponseBean.class, params);
                no_card_pay_card_no.setText("");
            }
        };
        DialogInterface.OnClickListener cancelClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        };
        showAlertDialog(this, getString(R.string.tip), getString(R.string.no_card_pay_delete), false, okClickListener, cancelClickListener);


    }

    public void getMrchantType() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, ZZTongActivity.newBankFlag);
        params.put(BaseProtocolKey.TRADETYPE, "6");//多费率6表示银联在线 7 表示银联快捷
        doJsonPost(this, ZZTongActivity.Do_GetMerchantTypeList, MerchantTypeList.class, params);
    }


    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(getString(R.string.no_card_pay_title), true);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.no_card_pay_camera_btn) {
            if (AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
                goToIsCardSCanActivity();
            } else {
                initCameraPermission();
                return;
            }
        } else if (v.getId() == R.id.no_card_pay_card_btn) {
            doHistoryBankCardList();
        } else if (v.getId() == R.id.no_card_pay_next_btn) {
            if (AndPermission.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                doNext();
            } else {
                initFindLocationPersmission();
            }
        } else if (v.getId() == R.id.ll_arrow) {
            showMerchTypePop(typeList);
        }
    }

    private void doHistoryBankCardList() {
        Hashtable<String, String> params = new Hashtable<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("tradeType", "1");
        doJsonPost(this, Do_GetHistoryBankCardList, HistoryBankCardListBean.class, params);
    }

    private void doNext() {
        String cardNo = no_card_pay_card_no.getText().toString();
        cardNo = cardNo.replace(" ", "");
        if (no_card_pay_card_no.isEnabled()) {
            if (!CommonUtils.isLegalCard(cardNo)) {
                this.showAlertDialog(this, getString(R.string.tip), getString(R.string.input_right_card_no_tip));
                return;
            }
        }

        if (bIsShowMerchantType == true) {
            if (TextUtils.isEmpty(mMerchantType) || TextUtils.isEmpty(mMerchantTypeCode)) {
                this.showAlertDialog(this, getString(R.string.tip), getString(R.string.selectMerchType));
                return;
            }
        }
        String merchantCode = AccountUtils.getMerchantCode(this);
        String amount = String.valueOf(Double.valueOf(mAmount).intValue());
        String channel = ClientEngine.CHANNEL;
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        if (TextUtils.isEmpty(address)) {
            getCurrentLocation();
            return;
        }
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String location = latitude.toString() + "," + longtitude.toString();
        String clientChannel = ZZTConfig.UPDATE_CHANNEL;
        String clientVersion = "v" + ClientEngine.VERSION;
        String host;
        if (ZZTConfig.isTesting) {
            host = NOCARDPAYMENTURL_MY_TEST + "hpayMicroWap/";
        } else {
            host = NOCARDPAYMENTURL_MY + "hpayMicroWap/";
        }
        String url1;
        url1 = host + "nocardpay/zztNoCardPayTransfer.htm?" +
                "cardNo=" + cardNo +
                "&merchantCode=" + merchantCode +
                "&amount=" + amount +
                "&channel=" + channel +
                "&address=" + address +
                "&location=" + location +
                "&clientChannel=" + clientChannel +
                "&clientVersion=" + clientVersion;
        String url;
        url = host + "nocardpay/zztNoCardPayTransfer.htm?";
        String tmp;
        if (no_card_pay_card_no.isEnabled()) {
            tmp = "cardNo=" + SecureManager.getInstance().des(cardNo, 1, des3Key);
        } else {
            String cardID = mBankCard.getCardID();
            tmp = "cardID=" + SecureManager.getInstance().des(cardID, 1, des3Key);
        }
        url += tmp;
        url +=
                "&merchantCode=" + SecureManager.getInstance().des(merchantCode, 1, des3Key);
        if (bIsShowMerchantType) {
            url += "&merchClassId=" + SecureManager.getInstance().des(mMerchantTypeCode, 1, des3Key);
        }

        url +=
                "&amount=" + SecureManager.getInstance().des(amount, 1, des3Key) +
                        "&channel=" + SecureManager.getInstance().des(channel, 1, des3Key) +
                        "&address=" + SecureManager.getInstance().des(address, 1, des3Key) +
                        "&location=" + SecureManager.getInstance().des(location, 1, des3Key) +
                        "&clientChannel=" + SecureManager.getInstance().des(clientChannel, 1, des3Key) +
                        "&clientVersion=" + SecureManager.getInstance().des(clientVersion, 1, des3Key);
        HPLog.i(HPLog.YL_TAG, "加密 url:" + url);
        HPLog.i(HPLog.YL_TAG, "未加密 url:" + url1);
        Intent intent = new Intent(this, ShowHtmlActivity.class);
        intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, "无卡支付");
        intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, url);
        startActivity(intent);
        this.finish();
    }

    private void showRecentCardNoListWindow(View v) {
        View popupView = getLayoutInflater().inflate(R.layout.layout_no_card_pay_list_card_no, null);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        }


//        int[] location = new int[2];
//        v.getLocationOnScreen(location);
//        mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-mPopupWindow.getHeight());

        ListView listView = (ListView) popupView.findViewById(R.id.no_card_pay_card_no_lv);
        listView.setAdapter(mNoCardPayListCardNoAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NoCardPayListCardNoAdapter aNoCardPayListCardNoAdapter = (NoCardPayListCardNoAdapter) parent.getAdapter();
                if (aNoCardPayListCardNoAdapter.getCount() == 1) {
                    return;
                } else if (aNoCardPayListCardNoAdapter.getCount() - 1 == position) {
                    doDeleteHistoryBankCardList();
                } else {
                    mBankCard = aNoCardPayListCardNoAdapter.getItem(position);
                    no_card_pay_card_no.setText(mBankCard.getCardNo());
                    no_card_pay_card_no.setEnabled(false);
                    mPopupWindow.dismiss();
                }
            }
        });
//        List<BankCardInfo> data = new ArrayList<BankCardInfo>();
//        data.add(new BankCardInfo());
//        data.add(new BankCardInfo());
//        data.add(new BankCardInfo());
//        mNoCardPayListCardNoAdapter.setData(data);
        mNoCardPayListCardNoAdapter.notifyDataSetChanged();
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            v.getLocationInWindow(a);
            mPopupWindow.showAtLocation(NoCardPayActivity.this.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + v.getHeight() + CommonUtils.dp2px(20));
        } else {
            mPopupWindow.showAsDropDown(v);
        }

        mPopupWindow.update();
//        mPopupWindow.showAsDropDown(v);

//        int[] location = new int[2];
//        v.getLocationOnScreen(location);
//        mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-mPopupWindow.getHeight());
    }


    private void goToIsCardSCanActivity() {
        if (useScanType == 0) {
            try {
                Intent intent = new Intent(this, ISCardScanActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                // 指定SDK相机模块ISCardScanActivity提示字符串
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_TIPS, "请将银行卡放在框内识别");
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, BitmapUtil.trimed_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, BitmapUtil.origianl_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, BaseProtocolKey.KEY_CC_CARD);
                HPLog.e("isCCCard", "KEYS=" + BaseProtocolKey.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        } else if (useScanType == 1) {
            try {
                Intent intent = new Intent(this, PreviewActivity.class);
                // 指定SDK相机模块ISCardScanActivity四边框角线条,检测到银行卡图片后的颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_MATCH, 0xffff0000);
                // 指定SDK相机模块ISCardScanActivity四边框角线条颜色，正常显示颜色
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_COLOR_NORMAL, 0xff00ff00);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_ORIENTATION, ISCardScanActivity.ORIENTATION_VERTICAL);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_NUMBER_IMG, false);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_TRIMED_IMG, BitmapUtil.trimed_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_GET_ORIGINAL_IMG, BitmapUtil.origianl_card_img);
                intent.putExtra(ISCardScanActivity.EXTRA_KEY_APP_KEY, BaseProtocolKey.KEY_CC_CARD);
                startActivityForResult(intent, isCardRequestCode);
            } catch (Exception e) {
                HPLog.e("isCCCard", "出错了");
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == REQUEST_CODE_CAMERA_GETCARDNO) {
            if (AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
                goToIsCardSCanActivity();
            } else {
                initCameraPermission();
            }
        } else if (requestCode == REQUEST_CODE_FINDLOCATION) {
            if (AndPermission.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                doNext();
            } else {
                initFindLocationPersmission();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HPLog.i("result", "requestCode:" + requestCode);

        if (requestCode == isCardRequestCode) {
            no_card_pay_card_no.setEnabled(true);
            if (resultCode == RESULT_OK && data != null) {
                long time = data.getLongExtra(ISCardScanActivity.EXTRA_KEY_TIME, 0);
                CCREngine.ResultData result = (CCREngine.ResultData) data.getSerializableExtra(ISCardScanActivity.EXTRA_KEY_RESULT);
                // 卡号
                String cardNumber = result.getCardNumber();
                no_card_pay_card_no.setText(cardNumber);

            } else {
                no_card_pay_card_no.setText("");
                HPLog.e("isCCCard", "返回失败,未拍照");
            }
        } else if (requestCode == REQUEST_CODE_CAMERA_GETCARDNO) {
            if (AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
                goToIsCardSCanActivity();
            } else {
                initCameraPermission();
            }
        } else if (requestCode == REQUEST_CODE_FINDLOCATION) {
            if (AndPermission.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                doNext();
            } else {
                initFindLocationPersmission();
            }
        }

    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        boolean bResult = super.netJsonResponse(action, resp, showAlert);
        if (bResult) {
            return true;
        }
        if (action.equals(ZZTongActivity.DO_zztGetMerchantInfo)) {
            mMerchantInfo = (MerchantInfo) resp;
            String name = mMerchantInfo.getName();
            name = SecureManager.getInstance().des(name, 0, null);
            no_card_pay_user_name_tv.setText(name);
        } else if (action.equals(ZZTongActivity.Do_GetHistoryBankCardList)) {
            HPLog.i(HPLog.YL_TAG, "Do_GetHistoryBankCardList");
            mHistoryBankCardListBean = (HistoryBankCardListBean) resp;
            List<HistoryBankCardListBean.ListBean> list = mHistoryBankCardListBean.getList();
            mNoCardPayListCardNoAdapter.setData(list);
            mNoCardPayListCardNoAdapter.notifyDataSetChanged();
            showRecentCardNoListWindow(ll_card);
        } else if (action.equals(ZZTongActivity.Do_DeleteHistoryBankCardList)) {
            if (resp.getResponseCode().equals("0")) {
                no_card_pay_card_no.setEnabled(true);
            }
        } else if (action.equals(ZZTongActivity.Do_GetMerchantTypeList)) {
            merchant_type_btn.setEnabled(true);
            MerchantTypeList merchantTypeList = (MerchantTypeList) resp;
            if (merchantTypeList.getList() == null || merchantTypeList.getList().size() == 0) {
                ll_merchant_type.setVisibility(View.GONE);
                bIsShowMerchantType = false;

            } else {
                ll_merchant_type.setVisibility(View.VISIBLE);
                bIsShowMerchantType = true;
                for (MerchantTypeList.MerchantType enMerchantType : merchantTypeList.getList()) {
                    MerchantTypeList.MerchantType desMerchantType = new MerchantTypeList.MerchantType();
                    String typeCode = SecureManager.getInstance().des(enMerchantType.getMerchClassId(), 0, null);
                    String typeName = SecureManager.getInstance().des(enMerchantType.getMerchClassName(), 0, null);
                    String merchantTypeFee = SecureManager.getInstance().des(enMerchantType.getMerchClassFeeRate(), 0, null);
                    String merchantTypeFeeIncrement = SecureManager.getInstance().des(enMerchantType.getMerchClassFeeIncrement(), 0, null);
                    desMerchantType.setMerchClassId(typeCode);
                    desMerchantType.setMerchClassName(typeName);
                    desMerchantType.setMerchClassFeeRate(merchantTypeFee);
                    desMerchantType.setMerchClassFeeIncrement(merchantTypeFeeIncrement);
                    typeList.add(desMerchantType);
                }
            }


        }
        return false;
    }

    /**
     * 初始化相机权限
     */
    private void initCameraPermission() {
        AndPermission.with(this).permission(Manifest.permission.CAMERA)
                .requestCode(REQUEST_CODE_CAMERA_GETCARDNO)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(NoCardPayActivity.this, rationale).show();
                    }
                }).send();
    }

    /**
     * 初始化定位权限
     */
    private void initFindLocationPersmission() {
        AndPermission.with(this).requestCode(PermissionRequestCode.REQUEST_CODE_FINDLOCATION)
                .permission(Manifest.permission.ACCESS_FINE_LOCATION)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(NoCardPayActivity.this, rationale).show();
                    }
                }).send();
    }

    /**
     * show merchantype
     *
     * @param data
     */
    private void showMerchTypePop(final List<MerchantTypeList.MerchantType> data) {
        MerchantTypeAdapter merchantTypeAdapter = new MerchantTypeAdapter(this);
        merchantTypeAdapter.setmLists(data);
        merchant_type_btn.setBackgroundResource(R.drawable.arrow_up);
        View popView = getLayoutInflater().inflate(R.layout.layout_merch_type_list, null);
        final PopupWindow popupWindow = new PopupWindow(popView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        ListView lv_merchType = (ListView) popView.findViewById(R.id.lv_type);
        lv_merchType.setAdapter(merchantTypeAdapter);
        lv_merchType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mMerchantTypeBean = data.get(position);
                mMerchantType = mMerchantTypeBean.getMerchClassName();
                mMerchantTypeCode = mMerchantTypeBean.getMerchClassId();
                rates_info_ll.setVisibility(View.VISIBLE);
                no_card_pays_merchant_type_tv.setText(mMerchantTypeBean.getMerchClassName());
                double fee = Double.valueOf(mMerchantTypeBean.getMerchClassFeeIncrement());
                rates_tv.setText(mMerchantTypeBean.getMerchClassFeeRate() + "%+" + CommonUtils.formatMoneyDouble(ArithUtil.div(fee, 100d)));
                double rates = Double.valueOf(mMerchantTypeBean.getMerchClassFeeRate());
                double service_charge = ArithUtil.mul(ArithUtil.div(rates, 100d), mAmount) + Double.valueOf(fee);
                service_charge = CommonUtils.getCeil(ArithUtil.div(service_charge, 100d), 2);
                service_charge_tv.setText(CommonUtils.formatMoneyDouble(service_charge) + "元");
                double arrival_amount =ArithUtil.div( mAmount, 100d) - service_charge;
                arrival_amount_tv.setText(CommonUtils.formatMoneyDouble(arrival_amount) + "元");
                popupWindow.dismiss();
            }
        });
        if (android.os.Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            ll_merchant_type.getLocationInWindow(a);
            popupWindow.showAtLocation(NoCardPayActivity.this.getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + ll_merchant_type.getHeight() + CommonUtils.px2dp(20));
        } else {
            popupWindow.showAsDropDown(ll_merchant_type);
        }
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                merchant_type_btn.setBackgroundResource(R.drawable.arrow_down);
            }
        });
    }
}
